package com.example.wearing.wardrobe;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProvider;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wearing.R;
import com.example.wearing.find.AddPostActivity;
import com.example.wearing.find.PostDetailActivity;
import com.example.wearing.javabean.Clothes;
import com.example.wearing.javabean.Post;
import com.example.wearing.tools.BitmapBinder;
import com.example.wearing.tools.ImageUtil;
import com.example.wearing.tools.KindListAdapter;
import com.example.wearing.tools.ClothesListAdapter;
import com.example.wearing.tools.PostAdapter;
import com.example.wearing.tools.ReplyAdapter;
import com.example.wearing.user.AlterUserImgActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.w3c.dom.Text;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class WardrobeFragment extends Fragment {

    private WardrobeViewModel mViewModel;
    FloatingActionButton fab;
    private Handler handler;

    int c_id, userId;
    String currentKind = "无分类"; //用于修改、删除数据时，留存kind
    final String[] types = {"无分类", "上装", "下装", "内衣", "鞋子", "包包", "配饰"}; //种类列表

    String username;
    ArrayList<String> kindList = new ArrayList<>();
    private ArrayList<Clothes> clothesList = new ArrayList<>();
    private final static String TAG = "WardrobeFragment";
    String jdbcUrl, jdbcUser, jdbcPassword;

    private ProgressBar bar;
    TextView nodata;
    ListView kindListView;
    GridView moreListView;
    KindListAdapter kindListAdapter;  //左侧列表adapter
    ClothesListAdapter clothesListAdapter;  //右侧列表adapter


    public static WardrobeFragment newInstance() {
        return new WardrobeFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.wardrobe_fragment, container, false);
        kindListView = view.findViewById(R.id.classify_mainlist);
        moreListView = view.findViewById(R.id.classify_morelist);
        fab = view.findViewById(R.id.addClothesBtn);
        bar = view.findViewById(R.id.progressBar);
        nodata = view.findViewById(R.id.nodataText);
        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(WardrobeViewModel.class);
        // TODO: Use the ViewModel

        //悬浮按钮
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "onClick: 点击悬浮钮，进入添加衣物界面······");
                //获取当前kind
                int position = kindListAdapter.getNowSelectedIndex();
                currentKind = types[position];
                //进入发布衣物页面
                Intent addClothesIntent = new Intent(getActivity(), AddClothesActivity.class);
                addClothesIntent.putExtra("c_flag", 1);
                startActivityForResult(addClothesIntent, 10);
            }
        });

        init(); //初始化列表数据、查找username
        searchAndAdapter(); //查询所有帖子并设置adapter显示

        //点击分类，进行切换
        kindListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                kindListAdapter.setNowSelectedIndex(position);
                initClothesAdapter(kindList.get(position));
            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if(requestCode == 10 && resultCode == 20){
            //添加衣物后，更新衣物的信息，更新adapter
            Thread thread = new Thread(selectClothesRun);
            thread.start();
        } else if(requestCode == 30 && resultCode == 40){
            //更改衣物信息后，更新adapter
            Thread thread = new Thread(selectClothesRun);
            thread.start();
        }
    }


    //查询当前所有衣物信息
    private void searchAndAdapter() {
        Log.i(TAG, "searchAndAdapter: 查询衣物信息中······");

        handler = new Handler(){
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void handleMessage(@NonNull Message msg){
                Log.i(TAG, "handleMessage: 收到消息");

                if(msg.what == 1){
                    //接收消息
                    int res = (int) msg.obj;
                    if(res == 1){
                        Log.i(TAG, "done: 查询成功");
//                        Toast.makeText(getActivity().getApplicationContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "handleMessage: 衣物数量:"+clothesList.size());
//                        kindListAdapter.setNowSelectedIndex(0);
//                        initClothesAdapter("无分类");  //设置默认选中第一项
                        initClothesAdapter(currentKind);  //设置默认选中第一项

                    }else if(res == 2){
                        //查询帖子失败
                        Log.i(TAG, "done: 查询失败");
                        Toast.makeText(getActivity().getApplicationContext(), "刷新失败", Toast.LENGTH_SHORT).show();
                    }

                    //切换显示状态
                    bar.setVisibility(View.GONE);
                    //没有获得数据时显示
                    moreListView.setEmptyView(nodata);
                    moreListView.setVisibility(View.VISIBLE);
                }else if(msg.what == 2){
                    Log.i(TAG, "handleMessage: 收到删除某件衣物的消息");
                    //更新适配器
                    initClothesAdapter(currentKind);  //设置默认选中第一项
                }
                super.handleMessage(msg);
            }
        };


        Thread thread = new Thread(selectClothesRun);
        thread.start();
    }

    //初始化每个分类下 衣物列表
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initClothesAdapter(String kind) {
        //根据kind对arraylist进行筛选
        ArrayList<Clothes> resList = (ArrayList<Clothes>) clothesList.stream().filter(c -> kind.equals(c.getC_type())).collect(Collectors.toList());
        clothesListAdapter = new ClothesListAdapter(getActivity(), R.layout.clothes_list, resList);
        moreListView.setAdapter(clothesListAdapter);

        //点击事件
        moreListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                clothesListAdapter.setNowSelectedIndex(position);
                Log.i(TAG, "onItemClick: 点击position:"+position);
                Clothes alterClothes = (Clothes) moreListView.getItemAtPosition(position);
                currentKind = alterClothes.getC_type();
                //跳转修改界面——同add页面，这次传递信息到addClothesActivity————参考post详情页跳转传递信息
                Intent alterClothesIntent = new Intent(getActivity(), AddClothesActivity.class);
                alterClothesIntent.putExtra("c_flag", 2);
                alterClothesIntent.putExtra("c_id", alterClothes.getC_id());
                alterClothesIntent.putExtra("c_type", alterClothes.getC_type());
                alterClothesIntent.putExtra("c_name",alterClothes.getC_name());
                alterClothesIntent.putExtra("c_color",alterClothes.getC_color());
                Bundle bundle = new Bundle();
                Bitmap bitmap = ImageUtil.base64ToImage(alterClothes.getC_img());
                bundle.putBinder("c_img", new BitmapBinder(bitmap));
                alterClothesIntent.putExtras(bundle);
                startActivityForResult(alterClothesIntent, 30);

            }
        });

        moreListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("提示")
                        .setMessage("请确认是否删除当前数据？")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.i(TAG, "onClick: 删除对话框事件处理");
                                Clothes clothes = (Clothes) moreListView.getItemAtPosition(position);
                                c_id = clothes.getC_id();
                                currentKind = clothes.getC_type();
                                //删除arraylist中信息
                                clothesList.remove(clothes);
                                //开启线程，从数据库中删除该记录
                                Thread thread2 = new Thread(deleteClothesRun);
                                thread2.start();
                                Log.i(TAG, "onActivityCreated: DB删除记录");
                            }
                        }).setNegativeButton("否", null);
                builder.create().show();

                return true;
            }
        });
        clothesListAdapter.notifyDataSetChanged();
    }

    //分类数据初始化
    private void init() {

        kindList.add("无分类");
        kindList.add("上装");
        kindList.add("下装");
        kindList.add("内衣");
        kindList.add("鞋子");
        kindList.add("包包");
        kindList.add("配饰");

        kindListAdapter = new KindListAdapter(getActivity(), R.layout.kind_list, kindList);
        kindListView.setAdapter(kindListAdapter);

        //从SharedPreferences中获取用户名
        SharedPreferences sp = getActivity().getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(getActivity());
        username = sp.getString("user_name","");
        userId = sp.getInt("user_id",0);
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");

    }

    //创建线程类，实现Runnable接口，用于查询所有衣物信息
    private Runnable selectClothesRun = new Runnable() {
        @Override
        public void run() {
            try {
                Log.i(TAG, "run: 开始查询所有衣物111");
                Class.forName("com.mysql.jdbc.Driver");
                Log.i(TAG, "run: 222");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
                Log.i(TAG, "run: 3333");
                String sql = "select * from clothes where c_uid="+userId+"";
                Statement st = (Statement)cn.createStatement();

                int resCode;
                try {
                    ResultSet rs = st.executeQuery(sql);
                    System.out.println("连接数据库成功");

                    rs.last(); // 将光标移动到最后一行
                    int rowCount = rs.getRow(); // 得到当前行号，即结果集记录数
                    Log.i(TAG, "run: 数量rowcount:"+rowCount);
                    rs.beforeFirst();//将光标移回首行

                    clothesList.clear();    //清空clothesList
                    //查询出数据，将其放在List<Clothes>中，使用adapter将其显示在列表里
                    while (rs.next()){
                        Clothes clothes = new Clothes();
                        clothes.setC_id(rs.getInt("c_id"));
                        clothes.setC_color(rs.getString("c_color"));
                        clothes.setC_type(rs.getString("c_type"));
                        clothes.setC_name(rs.getString("c_name"));
                        clothes.setC_img(rs.getString("c_img"));
                        clothesList.add(clothes);
                    }
                    resCode = 1;
                    rs.close();
                } catch (SQLException e) {
                    Log.i(TAG, "run:SQL fail!!!__"+e);
                    e.printStackTrace();
                    resCode = 2;
                }

                //发送消息
                Message msg = handler.obtainMessage(1, resCode);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---查询结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__"+e);
                e.printStackTrace();
            }
        }
    };

    //长按删除衣物
    private Runnable deleteClothesRun = new Runnable() {
        @Override
        public void run() {

            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
                String sql = "delete from clothes where c_id = "+ c_id;
                Statement st = (Statement) cn.createStatement();
                int result = st.executeUpdate(sql);// 返回值代表收到影响的行数
                System.out.println("删除衣物——连接数据库成功");

                //发送消息
                Message msg = handler.obtainMessage(2, result);
                handler.sendMessage(msg);
                Log.i(TAG, "run: 消息已发送---删除结果");

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
        }
    };


}